

// pages/contact/contact.js
const appData = getApp();
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var util = require('../../utils/util.js');

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0,
    senderPic:'',
    senderName:'',
    sender:'',
    myHead:'',
    msgList:[],
    isClick:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //双方的个人信息
    this.setData({
      senderPic:options.head,
      senderName:options.name,
      sender:options.id,
      myHead:appData.globalData.userInfo.avatarUrl
    })
    wx.request({
      url:'http://124.222.95.170:21311/user/getMyId',
      method:'GET',
      header: {
        'Cookie': wx.getStorageSync('sessionid')
      },
      success:(res)=>{
        // console.log(res.data)
        wx.setStorageSync('myId', res.data.data)
      }
    })
    this.timing()
  },
  timing(){
    var interval = setInterval(() => {
      this.getRecords()
      this.updateFinalMsg()
    }, 1000);
  },
  getRecords(){
    var tempList = [] //用来放之前的聊天记录
    var senderId = this.data.sender
    if(wx.getStorageSync(senderId) || wx.getStorageSync(senderId).length != 0) tempList = wx.getStorageSync(senderId)
    var len = tempList.length
    var localChat = wx.getStorageSync('localMsg')
    var index = localChat.findIndex(item=>{
      return senderId === item.senderId
    })
    var newmsg = []
    if(index != -1){
      var newMsg = localChat[index].messageList //当前对方的最新消息集合
    }
   
    if(newMsg.length != 0){
      for(var i = 0; i < newMsg.length; i++){
        let obj = {
          speaker:'server',
          type:'text',
          content:newMsg[i].content,  //单条消息
          date:localChat[index].finalTime
        }
        tempList.push(obj)
        if(appData.globalData.isClick == true){
          localChat[index].messageList = [] //去除未读消息
        }
        
      }
      this.setData({
        msgList:tempList
      })
      this.setData({
        toView: 'msg-' + (this.data.msgList.length - 1)
      })
      wx.setStorageSync(senderId, tempList) //更新聊天记录
      wx.setStorageSync('localMsg', localChat) //更新本地新消息数组
      
    }
  },
  updateFinalMsg(){
    var time = this.data.myDate
    var templist = []
    if(wx.getStorageSync(this.data.sender)){
      templist = wx.getStorageSync(this.data.sender)
      var len = templist.length 
      var local = wx.getStorageSync('localMsg')
      var index = local.findIndex(item =>{
        return this.data.sender === item.senderId
      })
      local[index].latestMsg = templist[len - 1].content
      local[index].finalTime = templist[len - 1].date
      wx.setStorageSync('localMsg', local)
    }
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    appData.globalData.isClick = true
    this.setData({
      isClick:appData.globalData.isClick
    })
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 获取聚焦
   */
  focus: function(e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (this.data.msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function(e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (this.data.msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function(e) {
    var myDate = util.formatTime(new Date());
    var senderId = this.data.sender
    var tempList = wx.getStorageSync(senderId)
    tempList.push({
      speaker: 'customer',
      contentType: 'text',
      content: e.detail.value,
      date:myDate.substring(10)
    })
    //清空输入框
    inputVal = '';
    //参数和变量名称一致，可用一个值代替
    this.setData({
      msgList:tempList,
      inputVal,
    });
    wx.setStorageSync(senderId, tempList)
    wx.request({
      url: 'http://124.222.95.170:21311/chat/sendMessage',
      method:'POST',
      header: {
        'Cookie': wx.getStorageSync('sessionid')
      },
      data:
      {
        "receiverId": senderId,
        "type": 0,
        "content": e.detail.value
      },
      success:(res)=>{
        console.log('发送成功')
      }
    })
  },

  /**
   * 退回上一页
   */
  // toBackClick: function() {
  //   wx.navigateBack({})
  // },
  onHide: function () {
  
  }
})
